<?php

namespace Modules\Order\Entities;

use Illuminate\Database\Eloquent\Builder;
use Modules\Core\Entities\BaseEntity as Model;
use Modules\Order\Entities\AgentOrder;
use Modules\Order\Entities\BaseOrder;

use ThrowException;

class AgentPayRecord extends Model
{
    // 代付记录

    protected $guarded = [];
    protected $table = 'agent_pay_records';

    static public $resourceName = '代付记录';

    public function user()
    {
        return $this->belongsTo('\Modules\User\Entities\User', 'user_id');
    }

    public function order()
    {
        return $this->belongsTo('\Modules\Order\Entities\BaseOrder', 'order_id');
    }

    public function agent_order()
    {
        return $this->belongsTo('\Modules\Order\Entities\BaseOrder', 'agent_order_id');
    }

    // 创建代付记录
    static public function  createWith($order)
    {
        $info = [
            'user_id' => $order->user_id,
            'order_id' => $order->id,
        ];

        return self::create($info);
    }

    public function checkStatus()
    {
        // 待支付的代付记录需要检查一下状态
        if ($this->status === 0) {
            if (!$this->order || $this->order->union_status !== 'pay_pending') {
                $this->update([
                    'status' => 3
                ]);
            }
        }
    }

    // 创建代付的订单
    public function createAgentOrder($user)
    {
        $order = $this->order;

        $skuableMaps = [
            [
                'skuable' => [
                    'title' => '代付请求',
                    'money_price' => $order->pay_money_price,
                ],
                'total' => 1
            ]
        ];

        $agentOrder = AgentOrder::initWith($skuableMaps, $user);
        $agentOrder->is_visible = 0;
        $agentOrder->createAll();

        $this->update([
            'agent_user_id' => $user->id,
            'agent_order_id' => $agentOrder->id 
        ]);

        return $agentOrder;
    }

    // 获取代付的设置
    public function getPayConfig($user)
    {
        $agentOrder = $this->createAgentOrder($user);

        // if (!$this->agent_order) {
        // }
        // else {
        //     $agentOrder = $this->agent_order;
        // }

        return $agentOrder->payByWechat('miniapp');
    }


    // 完成代付
    public function finishPay()
    {
        $order = BaseOrder::getDerivedOrder([
            'id' => $this->order_id
        ]);

        $order->completePay([
            'pay_type' =>  'agent_pay'
        ]);

        $this->update([
            'status'  => 2,
            'paid_at' => now()
        ]);
    }
}
